// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)

function resolve (modules, moduleName, value) {
  if (moduleName.indexOf('/') !== -1) {
    let temp = modules
    let mm = modules
    let names = moduleName.split('/')
    for (let index in names) {
      let name = names[index]
      if (!mm[name]) {
        mm[name] = {}
      }
      temp = mm
      mm = mm[name]
      if (String(index) === String(names.length - 1)) {
        temp[name] = value.default
      }
    }
  } else {
    modules[moduleName] = value.default
  }
}

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  // 把模块中的方法全部加载上去
  resolve(modules, moduleName, value)
  return modules
}, {})

export default modules
